package com.pig4cloud.pig.ads.controller;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.ads.utils.ProgressEntity;
import com.pig4cloud.pig.common.core.constant.CacheConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cx
 * @version 1.0.0
 * @ClassName UploadController.java
 * @createTime 2020年11月19日 19:30:00
 */
@Slf4j
@RestController
@RequestMapping("/uploadFile")
public class UploadController {
	@Autowired
	private RedisTemplate redisTemplate;
	/**
	 * 获取上传进度
	 *
	 * @return
	 */
	@RequestMapping(value = "/uploadStatus")
	public R uploadStatus(HttpServletRequest request) {
		//HttpSession session = request.getSession();
		//ProgressEntity percent = (ProgressEntity) session.getAttribute("progressEntity");
		ProgressEntity percent = JSON.parseObject(String.valueOf(redisTemplate.opsForValue().get(CacheConstants.PROGRESS_ENTITY_+ SecurityUtils.getUser().getId())), ProgressEntity.class);
		log.info(">>>" + JSON.toJSONString(percent));
		if (null != percent){
			//当前时间
			long nowTime = System.currentTimeMillis();
			//已传输的时间
			long time = (nowTime - percent.getStartTime()) / 1000 + 1;
			//传输速度 ;单位：byte/秒
			double velocity = ((double) percent.getBytesRead()) / (double) time;
			//估计总时间
			double totalTime = percent.getContentLength() / velocity;
			//估计剩余时间
			double timeLeft = totalTime - time;
			//已经完成的百分比
			int percent1 = (int) (100 * (double) percent.getBytesRead() / (double) percent.getContentLength());
			//已经完成数单位:m
			double length = ((double) percent.getBytesRead()) / 1024 / 1024;
			//总长度  M
			double totalLength = (double) percent.getContentLength() / 1024 / 1024;
			StringBuffer sb = new StringBuffer();
			//拼接上传信息传递到jsp中
			sb.append(percent + ":" + length + ":" + totalLength + ":" + velocity + ":" + time + ":" + totalTime + ":" + timeLeft + ":" + percent.getItems());
			log.info(">>>百分比:"+percent1+">>>已传输时间:"+time+">>>剩余时间:"+timeLeft+">>>已经完成:"+length);
			Map<String,Object> resultMap = new HashMap<>();
			resultMap.put("percent",percent1);//已上传百分比
			resultMap.put("velocity",velocity);//传输速度 ;单位：byte/秒
			resultMap.put("time",time);//已传输时间
			resultMap.put("totalTime",totalTime);//总时间
			resultMap.put("timeLeft",timeLeft);//剩余时间
			resultMap.put("totalLength",totalLength);//总字节
			resultMap.put("length",length);//完成字节
			resultMap.put("items",percent.getItems());//目前正在读取第几个文件
			return R.ok(resultMap);
		}
		return R.ok(null,"上传已完成");
	}
}
